package com.perfree.service;

import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.perfree.entity.Peers;
import com.perfree.entity.Share;
import com.perfree.mapper.PeersMapper;
import com.perfree.mapper.ShareMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.List;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ShareService {

    private final ShareMapper shareMapper;

    private final PeersMapper peersMapper;

    public Share saveShareInfo(Share share) {
        //监测是否已经共享
        int count = shareMapper.selectCountByExample(Example.builder(Share.class)
                .where(Sqls.custom().andEqualTo("pathMd5", share.getPathMd5()))
                .build());
        if(count > 0) { //已经共享过了
            return getShareByMd5(share.getPathMd5());
        } else {
            share.setId(null);
            share.setPassword(RandomUtil.randomString(4));
            shareMapper.insertSelective(share);
            return share;
        }
    }


    public int deleteShareById(Integer id) {
        return shareMapper.deleteByPrimaryKey(id);
    }

    public Share getShareByMd5(String md5) {
        Example example = Example.builder(Share.class)
                .where(Sqls.custom().andEqualTo("pathMd5", md5))
                .build();
        return shareMapper.selectOneByExample(example);
    }


    public Peers getPeersByUserId(Integer userId) {
        return shareMapper.getPeersByUserId(userId);
    }

    public Peers getPeersById(Integer id) {
        return peersMapper.getPeersById(id);
    }

    public boolean validateShare(String md5, String password) {
        Example example = Example.builder(Share.class)
                .where(Sqls.custom().andEqualTo("pathMd5", md5).andEqualTo("password", password))
                .build();
        int c = shareMapper.selectCountByExample(example);
        return c > 0;
    }

    public List<Share> getShareTable(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return shareMapper.selectAll();
    }
}
